<?php
/**
 * Classe respons�vel pela l�gica para o PostgreSQL
 * 
 * @link        www.thewebmind.org
 * @version       1.0
 * @author      Jaydson Gomes <jaydson@thewebmind.org>
 * @author      Felipe Nascimento <felipenmoura@thewebmind.org>
 */
	class PostgreSQL implements dbmsInterface
	{
		public $attType= Array();
		public $adoName= Array();
		
		public function __construct()
		{
			$this->attType				= Array();
			$this->defaultPort			= '5432';
			$this->attType['key']		= "int8 default nextval(<mind_simpleQuoting><schemaname>.<tablename>_seq</mind_simpleQuoting>)";
			$this->attType['varchar']	= "varchar(<length>)";
			$this->attType['char']		= "char(<length>)";
			$this->attType['text']		= "text";
			$this->attType['date']		= "timestamp";
			$this->attType['blob']		= "bytea";
			$this->attType['file']		= "bytea";
			$this->attType['integer']	= "integer";
			$this->attType['bigint']	= "int8";
			$this->attType['smallint']	= "int2";
			$this->attType['int']		= "int4";
			$this->attType['time']		= "timestamp";
			$this->attType['dateTime']	= "timestamp";
			$this->attType['real']		= "float";
			$this->attType['boolean']	= "boolean";
			$this->attType['serial']	= "serial";
		}
		
		/**
		* Retorna o acronimo PDO
		* @return  String 
		*/
		public function getAcronymPDO(){
			return "pgsql";
		}
		
		/**
		* Gets how to select the schema
		* @name selectSchema
		* @return  String 
		*/
		public function selectSchema($schemaName){
			return "SET searchpath to ".$schemaName;
		}
		
		/**
		* Selects the schema
		* @name selectCurrentSchema
		* @return  resource
		*/
		public function selectCurrentSchema($dbConn, $schemaName){
			return pg_query($dbConn, "SET searchpath to ".$schemaName);
		}
		
		/**
		* Remover todas as constraints realcionadas à tabela recebida, e entao rmover a tabela
		* @return  String 
		*/
		public function removeTable($dbConn, $tableName){
			GLOBAL $_MIND;
			$r= pg_query($dbConn, " SELECT c.conname AS constraint_name,
								   t.relname AS table_name,
								   t2.relname AS references_table
								   FROM pg_constraint c
							  LEFT JOIN pg_class t  ON c.conrelid  = t.oid
							  LEFT JOIN pg_class t2 ON c.confrelid = t2.oid
							 WHERE c.contype= 'f'
							   AND t2.relname = '".$tableName."'");
			while($cur= pg_fetch_assoc($r))
			{
				$alter= pg_query($dbConn, "ALTER TABLE ".$cur['table_name']." DROP CONSTRAINT ".$cur['constraint_name']);
				if(!$alter)
					return false;
			}
			$r= @pg_query($dbConn, "DROP TABLE ".$tableName);
			
			$alter= @pg_query($dbConn, "DROP sequence ".$tableName."_".$_MIND['primaryKeyPrefix']."".$tableName."_seq");
			return $r && $alter? true : false;
		}
		
		/**
		* Recupera o ultimo erro
		*
		* @param   Object $dbConn Conex�o
		* @return  String Erro
		*/
		function getLastError($dbConn)
		{
			return '<b>Error Message:</b> '.pg_last_error($dbConn);
		}
		
		/**
		* Conecta a base de dados
		*
		* @param   Object $ob Objeto com os dados para conex�o
		* @return  Object Resource
		*/
		function connectTo($ob)
		{
			if(is_array($ob))
				$connection = "host=".$ob['dbAddress']."  port=".$ob['dbPort']." dbname='".$ob['dbName']."'  user='".$ob['rootUser']."' password='".$ob['rootUserPwd']."'";
			else
				$connection = "host=".$ob->host."  port=".$ob->port." dbname='".$ob->name."'  user='".$ob->user."' password='".$ob->pwd."'";
				
			$connect = pg_connect($connection);
			return $connect;
		}
		
		/**
		* Desconecta
		*
		* @param   Object $dbCon Conex�o
		* @return  Object Resource
		*/
		function disconnectFrom($dbCon)
		{
			$connect = pg_close($dbCon);
			return $connect;
		}
		/**
		* Verifica se uma tabela existe
		*
		* @param   Object $dbCon Conex�o
		* @param   String $table Nome da tabela
		* @return  Boolean
		*/
		function tableExists($dbConn, $table)
		{
			$r= @pg_query($dbConn, "SELECT relname FROM pg_class WHERE relname = '".$table."'");
			//$r= @pg_query($dbConn, "select * from ".$table." limit 1");
			return (pg_num_rows($r) == 0)? false:true;
		}
		
		/**
		* Escreve o cabe�alho do arquivo SQL
		* @return  String Header		
		*/
		public function getHeader()
		{
			return "<mindComment>/*######################################################</mindComment>
<mindComment>  #   Generated by Mind ".(date('H:i m/d/Y'))."               #</mindComment>
<mindComment>  #   Generate PostgreSQL DataBase Commands         #</mindComment>
<mindComment>  ######################################################*/</mindComment>

";
		}
		
		/**
		* Escreve a fun��o para conex�o com o Postgres
		* @return  String Fun��o connectToPostgres()
		*/
		public function establishConnection()
		{
			return "function connectToPostgres(){
						\$db= '<dbname>';
						\$user= '<user>';
						\$pwd= '<pwd>';
						\$connection = \"host=<host>  port=<port> dbname='\$db'  user='\$user' password='\$pwd'\";
						\$connect = pg_connect(\$connection);
						return \$connect;
					}";
		}
		
		/**
		* Executa uma Query
		*
		* @param   Object $dbCon Conex�o
		* @param   String $qr Query
		* @return  Object Resource
		*/		
		public function query($dbCon, $qr)
		{
			return pg_query($dbCon, $qr);
		}
		
		/**
		* Fecha uma conex�o
		* @return  String Close
		*/
		public function closeConnection()
		{
			return  "pg_close(<query>)";
		}
		
		/**
		* Equivalente pg_fetch_array
		* @return  String pg_fetch_array
		*/	
		public function fetchArray()
		{
			return "pg_fetch_array(<source>)";
		}
		
		/**
		* Retorna o ultimo erro
		* @return  String pg_last_error
		*/	
		function lastError()
		{
			return 'pg_last_error(<source>)';
		}
		
		/**
		* Deleta um campo
		* @return  String pg_query
		*/
		public function dropField()
		{
			return "pg_query(<source>, 'alter table <table> drop column <column>'));";
		}
		
		/**
		* Adiciona um campo
		* @return  String pg_query
		*/
		public function addField()
		{
			return "pg_query(<source>, 'alter table <table> add column <column>'));";
		}		
		
		/**
		* Exclui uma tabela
		* @return  String drop
		*/
		public function dropTable()
		{
			return "pg_query(<source>, 'drop table <table>'));";
		}
		
		/**
		* Define um valor padr�o
		* @return  String default
		*/
		public function setDefaultValue()
		{
			return "default <defaultvalue>";
		}
		
		/**
		* Query
		* @return  String pg_query
		*/
		public function queryCommand()
		{
			return "pg_query(<query>)";
		}
		
		/**
		* Cria um campo
		* @return  String createField
		*/
		public function createFieldComment()
		{
			return "<constructor>COMMENT ON</constructor> <element>COLUMN</element> <schemaname>.<tablename>.<fieldname> <constructor>is</constructor> '<fieldComment>';";
		}
		
		/**
		* Cria um campo
		* @return  String createField
		*/
		public function createField()
		{
			return "<element><fieldname></element> <fieldtype> <allownull> <defaultvalue>";
		}
		
		/**
		* Cria uma foreign key
		* @return  String para criar Foreign Key
		*/
		public function createFK()
		{
			//return "<constructor>ALTER TABLE</constructor> <objTable><table></objTable> <obj>ADD CONSTRAINT</obj> <table>_<references> <obj>FOREIGN KEY<obj> <element><fk></element> <obj>REFERENCES</obj> <objTable><references></objTable> MATCH FULL;";
			return "<constructor>ALTER TABLE</constructor> <objTable><table></objTable> <obj>ADD CONSTRAINT</obj> <table>_<references> <obj>FOREIGN KEY<obj> (<element><fk></element>) <obj>REFERENCES</obj> <objTable><references></objTable>(<element><references_pk></element>) MATCH FULL;";
		}
		
		/**
		* Adiciona uma foreign key
		* @return  String para adicionar Primary Key
		*/
		public function addFK()
		{
			return "<constructor>FOREIGN KEY</constructor>(<element><foreignkey></element>) <obj>REFERENCES</obj> <element><references></element>";
		}
		
		/**
		* Primary Key padr�o
		* @return  String para Primary Key padr�o
		*/
		public function defaultPrimaryKey()
		{
			GLOBAL $_MIND;
			return "<element><fieldname></element> integer default nextval('<tablename>_".$_MIND['primaryKeyPrefix']."<tablename>_seq') <obj>unique</obj> <obj>not null</obj>";
		}
		
		/**
		* Cria uma primary key
		* @return  String para criar Primary Key
		*/	
		public function createPK()
		{
			return "<constructor>PRIMARY KEY</constructor>(<element><pk></element>)";
		}
		
		/**
		* Cria Tabela
		* @return  String para criar tabela
		*/	
		public function createTable()
		{
			GLOBAL $_MIND;
			return "	<mindComment>/* DDL: table <tablename> */</mindComment>
<constructor>CREATE</constructor> <obj>SEQUENCE</obj> <tablename>_".$_MIND['primaryKeyPrefix']."<tablename>_seq;
<constructor>CREATE</constructor> <obj>TABLE</obj> <objTable><tablename></objTable>
<element>(</element>
<fields>
<element>)</element>;";
		}
	}
?>